<!-- 标签管理 - 产品标签打印 - 生成 增补 置换  报废 -->
<template>
  <basic-container>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane
        :label="
          this.labelPrintType === 'generatedType'
            ? '标签生成及打印'
            : this.labelPrintType === 'supplementaryType'
            ? '标签增补及打印'
            : this.labelPrintType === 'replacementType'
            ? '标签置换及打印'
            : '标签报废'
        "
      >
        <el-row :gutter="20">
          <el-col :span="11">
            <avue-form
              v-if="labelPrintType === 'generatedType'"
              id="cpgeneratedForm"
              class="newFormStyle"
              key="1"
              ref="cpgeneratedForm"
              v-model="cpgeneratedForm"
              :option="cpgeneratedOption"
              @submit="cpgeneratedGenerate"
            >
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'supplementaryType'"
              id="cpSupplementaryForm"
              class="newFormStyle"
              key="2"
              ref="cpSupplementaryForm"
              v-model="cpSupplementaryForm"
              :option="cpSupplementaryOption"
              @submit="supplementaryGenerate"
            >
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'replacementType'"
              id="cpReplacementForm"
              class="newFormStyle"
              key="3"
              ref="cpReplacementForm"
              v-model="cpReplacementForm"
              :option="cpReplacementOption"
            >
              <!--              @submit="replacementGenerate"-->
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'scrapType'"
              id="cpScrapForm"
              class="newFormStyle"
              key="4"
              ref="cpScrapForm"
              v-model="cpScrapForm"
              :option="cpScrapOption"
              @submit="scrapGenerate"
            >
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <el-row>
              <el-col :span="15">
                <el-button style="float: right" v-if="labelPrintType === 'scrapType'" type="primary" size="small" @click="$refs.cpScrapForm.submit()">报废标签 </el-button>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <div class="sequenceInfo" v-if="labelPrintType != 'scrapType'">
              <el-row v-if="labelPrintType != 'replacementType'">
                <table border="1">
                  <tr>
                    <th colspan="4">序列号规则</th>
                  </tr>
                  <tr>
                    <th>规则名称</th>
                    <th>
                      <el-tooltip class="item" effect="dark" placement="top-start">
                        <i class="el-icon-info" style="color: #606266"></i>
                        <div slot="content">
                          [P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日, [S]：流水号, [N]：自定义字符。<br />[B]：后缀字符
                          <br />如：[YY][M][S][B] <br />若无流水号则没有[S],例如：[YY][M][B]
                        </div>
                        <!-- <el-button style="padding: 0; font-size: 18px" type="info" icon="el-icon-info" circle></el-button> -->
                      </el-tooltip>
                      序列号规则
                      <el-button
                        v-if="
                          sequenceRuleInfo.sequenceNoFormat &&
                          (sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 ||
                            sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1 ||
                            sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1 ||
                            sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1 ||
                            sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1)
                        "
                        style="padding: 5px"
                        type="primary"
                        icon="el-icon-edit"
                        circle
                        @click="openTimeConfigModel"
                      ></el-button>
                    </th>
                    <th>序列号规则位数</th>
                    <th>当前流水号</th>
                  </tr>
                  <tr style="height: 40px">
                    <td>{{ sequenceRuleInfo.name }}</td>
                    <td>
                      <div>{{ sequenceRuleInfo.sequenceNoFormat }}</div>
                      <div>{{ sequenceRuleInfo.sequenceNoFormatZh }}</div>
                    </td>
                    <td>
                      <div>{{ sequenceRuleInfo.snLength }}</div>
                    </td>
                    <td>{{ sequenceRuleInfo.sequenceNo }}</td>
                  </tr>
                </table>
                <table class="generateSerialNoInfo" border="1">
                  <tr>
                    <th colspan="4">序列号预览</th>
                  </tr>
                  <tr>
                    <div style="font-size: 15px; margin: 15px">序列号数量:{{ sequenceRuleInfo.quantity }}</div>
                    <div style="font-size: 15px; margin: 15px">起始序列号:{{ sequenceRuleInfo.sequenceNumberFrom }}</div>
                    <div style="font-size: 15px; margin: 15px">结尾序列号:{{ sequenceRuleInfo.sequenceNumberTo }}</div>
                  </tr>
                </table>
              </el-row>
              <el-row>
                <el-col :span="15">
                  <barcode-printer-template v-if="labelPrintType != 'scrapType'" ref="printInfo" templateType="MATERIAL" @getPrintInfo="getPrintInfo"></barcode-printer-template>
                </el-col>
                <el-col :span="15" class="btn-group">
                  <el-button v-if="labelPrintType === 'generatedType'" type="primary" size="small" @click="$refs.cpgeneratedForm.submit()">生成标签 </el-button>
                  <el-button v-if="labelPrintType === 'supplementaryType'" type="primary" size="small" @click="$refs.cpSupplementaryForm.submit()">增补标签 </el-button>

                  <!-- <el-button v-if="labelPrintType === 'scrapType'" type="primary" size="small" @click="$refs.cpScrapForm.submit()">报废标签</el-button> -->

                  <el-button v-if="labelPrintType != 'scrapType' && labelPrintType != 'replacementType'" type="primary" size="small" :loading="btnLoading" @click="batchPrinting"
                    >打印标签
                  </el-button>
                  <el-button v-if="labelPrintType === 'replacementType'" type="primary" size="small" @click="replacementGenerate">置换标签 </el-button>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-tabs type="border-card" class="informationLabel" style="margin-top: 20px">
      <el-tab-pane label="标签记录">
        <avue-crud
          :defaults.sync="recordDefaults"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecord"
          :table-loading="loading"
          :option="serialNoGenerationRecordOption"
          :data="serialnoData"
          :page="serialnoPage"
          @row-click="serialnoRowClick"
          @selection-change="selectionChange"
        >
          <template slot-scope="{ row }" slot="menu" v-if="labelPrintType === 'generatedType'">
            <div class="menu-option">
              <el-button icon="el-icon-printer" size="small" :disabled="row.isPrinted !== 1 || row.generationType === 'SCRAP'" type="text" @click="rowPrint(row)">
                重打
              </el-button>
            </div>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>

    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
    <!--重打弹窗-->
    <el-dialog append-to-body title="重打" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
      <div style="display: flex; justify-content: center; margin-bottom: 10px">
        <span style="color: red">注：仅需修改流水号即可，重打的起始流水号和结束流水号需在原流水号范围内</span>
      </div>
      <avue-form ref="printForm" v-model="repeatPrintInfo" :option="printInfoOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>重打</span></el-button>
        <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <print-time-input-form :visible.sync="printDialog" :other-info-option="otherInfoOption" @printInfo="printInputInfo"></print-time-input-form>
  </basic-container>
</template>

<script>
import { getYearWeek, showFailLog, showSuccessLog, showWarningLog } from '@/util/helpers';
import { getPrintFormMixin } from '@/mixins/getPrintFormMixin';
import printTimeInputForm from '@/components/print-time-input-form';
import {
  createSequenceByWorkorder,
  sequenceAppend,
  getSourceList,
  sequencePrint,
  sequenceGenerationSum,
  generationPreview,
  count
} from '@/api/product/product-label-create-print';
import { mapGetters } from 'vuex';
import { printTest } from '@/api/labelManagement/labelRecord';
import { getWorkOrderDetail } from '@/api/product/productSerialNumManage';

import { getDetail, getDetailLabel } from '@/api/admin/sequencedefinition';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template';
import barcodePrinterTemplate from '@/views/labelManagement/barcode-printer-template';
import OperationLog from '@/components/operation-log/operation-log';
import { getSeqNoRules } from '@/util/global';
import { getList, snPrint, sequenceScrap, snSequenceReplace, getLastPrintRecord, getLastPrint, sequenceNumber, queryWorkOrder } from '@/api/admin/barcode-record';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';

export default {
  //   name: 'barcodeGeneration',
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    barcodePrinterTemplate,
    OperationLog,
    printTimeInputForm
  },
  mixins: [getPrintFormMixin],
  data() {
    return {
      labelPrintType: 'generatedType',
      cpgeneratedForm: {}, //序列号生成信息,
      tableOption: {},
      timer: new Date().getTime(),
      loading: false,
      recordDefaults: {},
      serialNoGenerationRecordOption: {
        //工单产品序列号内容配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        selection: false, //多选
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        menu: false,
        highlightCurrentRow: true,
        column: [
          {
            label: '起始序列号',
            prop: 'sequenceNumberFrom'
          },
          {
            label: '结尾序列号',
            prop: 'sequenceNumberTo'
          },
          {
            label: '序列号数量',
            prop: 'quantity'
          },
          {
            label: '序列号位数',
            prop: 'snLength'
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            html: true,
            formatter: (val) => {
              switch (val.generationType) {
                case 'NORMAL':
                  return '正常';
                case 'SCRAP':
                  return '报废';
                case 'APPEND':
                  return '增补';
                case 'REPLACE':
                  return '置换';
                case 'REVORK':
                  return '撤销';
                default:
                  break;
              }
            }
          },
          {
            label: '操作人',
            prop: 'operatorName'
          },
          {
            label: '原因说明',
            prop: 'remark'
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              switch (val.isPrinted) {
                case 0:
                  return `<span class="text-yellow">未打印</span>`;
                case 1:
                  return `<span class="text-green">已打印</span>`;
                case 2:
                  return `<span class="text-red">部分打印</span>`;
                default:
                  return `<span class="text-red">报废</span>`;
                  break;
              }
            }
          }
        ]
      },
      serialnoData: [],
      serialnoPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      printInfo: {}, //打印机打印模版信息
      sequenceRuleInfo: {}, //产品序列号规则信息
      selectionInfo: {}, //选中生成记录
      printInfoModel: false,
      repeatPrintInfo: {},
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '起始流水号',
            prop: 'startSequenceNumber',
            span: 20
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNumber',
            span: 20
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          },
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          }
        ]
      },
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      //产品标签生成
      cpgeneratedOption: generatedDataOption(this), //
      //产品标签增补
      cpSupplementaryForm: {},
      cpSupplementaryOption: supplementaryDataOption(this),
      //产品标签置换
      cpReplacementForm: {},
      cpReplacementOption: replacementDataOption(this),
      //产品标签报废
      cpScrapForm: {},
      cpScrapOption: scrapDataOption(this),

      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      customAttributeList: [] //扩展属性
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo'])
  },
  mounted() {
    this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
    this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
    this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
    this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
    this.routeChange();
    this.serialnoData = [];
  },
  watch: {
    $route(val) {
      if (val.path.includes('/labelManagement/productLabel')) {
        this.routeChange();
      }
    }
  },
  methods: {
    routeChange() {
      this.serialnoData = [];
      this.sequenceRuleInfo = {};
      if (this.$route.path === '/labelManagement/productLabel/1') {
        this.labelPrintType = 'generatedType';
        //产品标签生成
        this.cpgeneratedOption = generatedDataOption(this);
        if (this.cpgeneratedForm.workOrderId) {
          this.getSequenceRecordById(this.cpgeneratedForm.workOrderId, 'NORMAL');
        }
      } else if (this.$route.path === '/labelManagement/productLabel/2') {
        this.labelPrintType = 'supplementaryType';
        //产品标签增补
        this.cpSupplementaryOption = supplementaryDataOption(this);
        if (this.cpSupplementaryForm.workOrderId) {
          this.getSequenceRecordById(this.cpSupplementaryForm.workOrderId, 'APPEND');
        }
      } else if (this.$route.path === '/labelManagement/productLabel/3') {
        this.labelPrintType = 'replacementType';
        //产品标签置换
        this.cpReplacementOption = replacementDataOption(this);
        if (this.cpReplacementForm.replaceSequenceNumber) {
          this.onceMore(this.cpReplacementForm.replaceSequenceNumber);
        }
      } else if (this.$route.path === '/labelManagement/productLabel/4') {
        this.labelPrintType = 'scrapType';
        //产品标签报废
        this.cpScrapOption = scrapDataOption(this);
        if (this.cpScrapForm.workOrderId) {
          this.getSequenceRecordById(this.cpScrapForm.workOrderId, 'SCRAP');
        }
      }
      this.getInventoryInfo(this.labelPrintType);
    },
    getInventoryInfo(labelPrintType) {
      if (labelPrintType === 'generatedType') {
        this.serialNoGenerationRecordOption.menu = true;
        let operatorName = this.findObject(this.serialNoGenerationRecordOption.column, 'operatorName');
        let reason = this.findObject(this.serialNoGenerationRecordOption.column, 'reasonCode');
        operatorName.hide = true;
        reason.hide = true;
      } else {
        this.serialNoGenerationRecordOption.menu = false;
        let operatorName = this.findObject(this.serialNoGenerationRecordOption.column, 'operatorName');
        let reason = this.findObject(this.serialNoGenerationRecordOption.column, 'reasonCode');
        operatorName.hide = false;
        reason.hide = false;
      }
    },
    /**
     * 序列号规则时间修改
     */
    openTimeConfigModel() {
      this.timeConfigModel = true;
      this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
      this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
      this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
      this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
      this.$nextTick(() => {
        let column = this.$refs.timeConfigForm.option.column;
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
          let year = this.findObject(column, 'year');
          year.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
          let month = this.findObject(column, 'month');
          month.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
          let day = this.findObject(column, 'day');
          day.display = true;
        }
      });
    },
    /**
     * 序列号规则中时间修改保存
     */
    onSaveTimeConfig() {
      //验证是否传递序列号规则中年份日期
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
        if (!this.timeConfig.year) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的年份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
        if (!this.timeConfig.month) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的月份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
        if (!this.timeConfig.week) {
          this.$message({
            type: 'error',
            message: '请输入序列号规则中的周数！'
          });
          // Helpers.selectInput('week');
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
        if (!this.timeConfig.day) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的日期！'
          });
          return;
        }
      }
      this.timeConfigModel = false;
    },
    //产品标签生成
    cpgeneratedGenerate(row, done) {
      let attr = {
        workOrderId: this.cpgeneratedForm.workOrderId,
        quantity: row.produceQuantity,
        sequenceDefinitionId: this.cpgeneratedForm.sequenceDefinitionId
        // timeConfig: this.timeConfig
      };
      // const json = {
      //   ...(row.BB_wo && { BB_wo: row.BB_wo }),
      //   ...(row.BH_wo && { BH_wo: row.BH_wo })
      // };
      // if (Object.keys(json).length) {
      //   attr.customizedFields = JSON.stringify(json);
      // }
      createSequenceByWorkorder(attr).then(
        (res) => {
          if (res.data.data.options && res.data.data.options != null) {
            let options = JSON.parse(res.data.data.options);
            if (options.isWarning) {
              this.$message({
                type: 'warning',
                message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
              });
              showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
            } else {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              showSuccessLog(res.data.msg);
            }
            this.cpgeneratedForm.produceQuantity = '';
          }
          this.getSequenceRecordById(this.cpgeneratedForm.workOrderId, 'NORMAL');
          this.getStartOrEndSequenceNumber('generatedType');
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },

    /**
     * 序列号增补
     */
    supplementaryGenerate(row, done) {
      let params = {
        workOrderId: this.cpSupplementaryForm.workOrderId,
        sequenceDefinitionId: this.cpSupplementaryForm.sequenceDefinitionId,
        quantity: this.cpSupplementaryForm.produceQuantity,
        remark: this.cpSupplementaryForm.remark
        // timeConfig: this.timeConfig
      };
      sequenceAppend(params).then(
        (res) => {
          if (res.data.data.options && res.data.data.options != null) {
            let options = JSON.parse(res.data.data.options);
            if (options.isWarning) {
              this.$message({
                type: 'warning',
                message: `${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`
              });
              showWarningLog(`${res.data.msg}，可用码段不足${options.warningQuantity}，剩余${options.availableQuantity}，请联系相关人员购买！`);
            } else {
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              showSuccessLog(res.data.msg);
            }
            this.cpSupplementaryForm.produceQuantity = '';
            this.cpSupplementaryForm.remark = '';
          }
          this.getSequenceRecordById(this.cpSupplementaryForm.workOrderId, 'APPEND');
          this.getStartOrEndSequenceNumber('supplementaryType');
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 序列号置换
     */
    replacementGenerate(row, done) {
      this.$refs.cpReplacementForm.validate((valid, done) => {
        if (valid) {
          if (!this.printInfo.printersId) {
            this.$message({
              type: 'warning',
              message: '请选择打印机！'
            });
            return;
          }
          if (!this.printInfo.labelTemplateId) {
            this.$message({
              type: 'warning',
              message: '请选择标签模版！'
            });
            return;
          }
          if (!this.fieldList.length) {
            this.handleReplacementGeneratePrint();
          } else {
            // 当标签模版绑定了数据源且设置了数据 打开其他信息弹窗
            this.printDialog = true;
          }
          done();
        }
      });
    },
    handleReplacementGeneratePrint(otherInfo = {}) {
      let params = {
        sequenceNumber: this.cpReplacementForm.replaceSequenceNumber,
        remark: this.cpReplacementForm.reason,
        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId
      };

      snSequenceReplace(params).then(
        (res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    /**
     * 序列号报废
     */
    scrapGenerate(row, done) {
      console.log(row, this.cpScrapForm);
      let params = {
        workOrderId: row.workOrderId,
        reason: row.reason,
        sequenceNumberFrom: row.startSequenceNumber,
        sequenceNumberTo: row.endSequenceNumber,
        sequenceGenerationId: row.sequenceGenerationId
      };

      sequenceScrap(params).then(
        (res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.cpScrapForm.startSequenceNumber = '';
          this.cpScrapForm.endSequenceNumber = '';
          this.cpScrapForm.serialQuantity = '';
          this.cpScrapForm.reason = '';
          this.cpScrapForm.sequenceGenerationId = '';
          this.getSequenceRecordById(row.workOrderId, 'SCRAP');
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 标签打印
     */
    batchPrinting() {
      try {
        if (!Object.keys(this.selectionInfo).length) {
          this.$message({
            type: 'warning',
            message: '请选择一条生产记录'
          });
          return;
        }
        if (!this.printInfo.printersId) {
          this.$message({
            type: 'warning',
            message: '请选择打印机！'
          });
          return;
        }
        if (!this.printInfo.labelTemplateId) {
          this.$message({
            type: 'warning',
            message: '请选择标签模版！'
          });
          return;
        }
        if (!this.fieldList.length) {
          this.handlePrintSequence();
        } else {
          // 当标签模版绑定了数据源且设置了数据 打开其他信息弹窗
          this.printDialog = true;
        }
      } catch (e) {
        console.warn(e);
      }
    },
    handlePrintSequence(otherInfo = {}) {
      let params = {
        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId,
        workOrderId: this.printWorkOrderId,
        sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
      };
      if (Object.keys(otherInfo).length) {
        params.printInput = JSON.stringify(otherInfo);
      }
      sequencePrint(params).then(
        (res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          this.getSequenceRecordById(this.printWorkOrderId);
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    // // 重打
    // rowPrint(row) {
    //   this.repeatPrintInfo.startSequenceNumber = row.sequenceNumberFrom;
    //   this.repeatPrintInfo.endSequenceNumber = row.sequenceNumberTo;
    //   this.repeatPrintInfo.generationId = row.id;
    //   this.printInfoModel = true;
    // },
    // 重打
    async rowPrint(row) {
      if (row.isPrinted != 1) {
        this.$message.warning('已打印状态的才可以重打');
        return;
      }
      try {
        const printer = await this.getDefaultPrinter(row.partNo);
        const { labelTemplateId = '', equipmentId = '', equipmentName = '', labelTemplateName = '' } = printer;
        this.repeatPrintInfo = {
          labelTemplateId: labelTemplateId,
          labelTemplateName: labelTemplateName,
          equipmentId: equipmentId,
          equipmentName
        };
      } catch (e) {
        console.warn(e);
      }
      this.repeatPrintInfo.startSequenceNumber = row.sequenceNumberFrom;
      this.repeatPrintInfo.endSequenceNumber = row.sequenceNumberTo;
      this.repeatPrintInfo.sequenceGenerationId = row.id;
      this.printInfoModel = true;
    },
    async getDefaultPrinter(partNo) {
      try {
        const res = await getLastPrintRecord({ partNo });
        return res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    //重打按钮接口
    printSubmit() {
      this.$refs.printForm.validate(async (valid, done) => {
        if (valid) {
          try {
            const params = {
              ...this.repeatPrintInfo,
              fromSequenceNumber: this.repeatPrintInfo.startSequenceNumber,
              toSequenceNumber: this.repeatPrintInfo.endSequenceNumber
            };
            delete params.startSequenceNumber;
            delete params.endSequenceNumber;
            const res = await snPrint(params);
            this.$refs.printForm.resetFields();
            this.printInfoModel = false;
            this.$message({
              type: 'success',
              message: '重打成功'
            });
            this.getSequenceRecordById(this.cpgeneratedForm.workOrderId);
          } catch (e) {
            console.warn(e);
          }
        }
      });
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'workorderModal') {
        this.printWorkOrderId = this._get(rowData, 'id', '');
        switch (this.labelPrintType) {
          case 'generatedType':
            this.cpgeneratedForm.partMasterId = this._get(rowData, 'productPartId', '');
            this.cpgeneratedForm.workOrderId = this._get(rowData, 'id', '');
            this.cpgeneratedForm.workOrderNo = this._get(rowData, 'workOrderNo', '');

            this.cpgeneratedForm.partNo = this._get(rowData, 'productPartNo', '');
            this.cpgeneratedForm.partName = this._get(rowData, 'productPartName', '');
            this.cpgeneratedForm.partModel = this._get(rowData, 'productPartModel', '');
            // this.cpgeneratedForm.sequenceDefinitionId = this._get(rowData, 'productSequenceDefinitionId', '');
            // this.cpgeneratedForm.sequenceName = this._get(rowData, 'sequenceDefinitionName', '');
            this.cpgeneratedForm.quantity = this._get(rowData, 'planQuantity', '');
            // this.getSequencedefinitionDetail(this.cpgeneratedForm.partMasterId, 'generatedType');
            this.getStartOrEndSequenceNumber('generatedType');
            this.preview(this.cpgeneratedForm, 1);
            this.getSequenceRecordById(this._get(rowData, 'id', ''), 'NORMAL');

            break;
          case 'supplementaryType':
            this.cpSupplementaryForm.partMasterId = this._get(rowData, 'partMasterId', '');

            this.cpSupplementaryForm.workOrderId = this._get(rowData, 'id', '');
            this.cpSupplementaryForm.workOrderNo = this._get(rowData, 'workOrderNo', '');

            this.cpSupplementaryForm.partNo = this._get(rowData, 'productPartNo', '');
            this.cpSupplementaryForm.partName = this._get(rowData, 'productPartName', '');
            this.cpSupplementaryForm.partModel = this._get(rowData, 'productPartModel', '');

            this.cpSupplementaryForm.sequenceDefinitionId = this._get(rowData, 'productSequenceDefinitionId', '');
            this.cpSupplementaryForm.sequenceName = this._get(rowData, 'sequenceDefinitionName', '');
            this.cpSupplementaryForm.quantity = this._get(rowData, 'planQuantity', '');

            // this.getSequencedefinitionDetail(this.cpSupplementaryForm.partMasterId, 'supplementaryType');
            this.getStartOrEndSequenceNumber('supplementaryType');
            this.preview(this.cpSupplementaryForm, 1);
            this.getSequenceRecordById(this._get(rowData, 'id', ''), 'APPEND');
            this.printTo({ partNo: this.cpSupplementaryForm.partNo, type: 'PRODUCT' });

            break;
          case 'scrapType':
            this.cpScrapForm.workOrderId = this._get(rowData, 'id', '');
            this.cpScrapForm.workOrderNo = this._get(rowData, 'workOrderNo', '');
            this.cpScrapForm.partNo = this._get(rowData, 'productPartNo', '');
            this.cpScrapForm.partName = this._get(rowData, 'productPartName', '');
            this.cpScrapForm.partModel = this._get(rowData, 'productPartModel', '');
            this.cpScrapForm.quantity = this._get(rowData, 'planQuantity', '');
            this.getSequenceRecordById(this._get(rowData, 'id', ''), 'SCRAP');
            break;
          default:
            break;
        }
      } else if (this.modalName === 'serialnoModal') {
        switch (this.labelPrintType) {
          case 'generatedType':
            this.cpgeneratedForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.cpgeneratedForm.sequenceName = this._get(rowData, 'name', '');

            this.$set(this.sequenceRuleInfo, 'name', this._get(rowData, 'name', ''));
            this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(rowData, 'sequenceNoFormat', ''));
            this.seqNoConvert();
            this.preview(this.cpgeneratedForm, 1);
            break;
          case 'supplementaryType':
            this.cpSupplementaryForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            this.cpSupplementaryForm.sequenceName = this._get(rowData, 'name', '');

            this.$set(this.sequenceRuleInfo, 'name', this._get(rowData, 'name', ''));
            this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(rowData, 'sequenceNoFormat', ''));
            this.seqNoConvert();
            this.preview(this.cpSupplementaryForm, 1);
            break;
          default:
            break;
        }
      } else if (this.modalName === 'printersModal') {
        this.repeatPrintInfo.equipmentId = this._get(rowData, 'id', '');
        this.repeatPrintInfo.equipmentName = this._get(rowData, 'name', '');
      } else if (this.modalName === 'labelTemplateModal') {
        this.repeatPrintInfo.labelTemplateId = this._get(rowData, 'id', '');
        this.repeatPrintInfo.labelTemplateName = this._get(rowData, 'fileName', '');
      }
    },
    printTo(data) {
      getLastPrint(data).then(
        (res) => {
          let { labelTemplateId = '', printerId = '', equipmentName = '', labelTemplateName = '' } = res.data;
          this.repeatPrintInfo = {
            labelTemplateId: labelTemplateId,
            labelTemplateName: labelTemplateName,
            equipmentId: printerId,
            equipmentName
          };
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    /*
     * 根据序列号规则ID查询详情
     */
    getSequencedefinitionDetail(partMasterId, type) {
      getDetailLabel(partMasterId).then((res) => {
        //获取标签模板
        this.printInfo.labelTemplateId = this._get(res.data.data, 'labelTemplateId', '');
        this.$refs.printInfo.model.labelTemplateName = this._get(res.data.data, 'labelTemplateName', '');

        if (type == 'generatedType') {
          this.cpgeneratedForm.sequenceDefinitionId = this._get(res.data.data, 'sequenceDefinitionId', '');
          this.cpgeneratedForm.sequenceName = this._get(res.data.data, 'sequenceDefinitionName', '');
        } else {
          this.cpSupplementaryForm.sequenceDefinitionId = this._get(res.data.data, 'sequenceDefinitionId', '');
          this.cpSupplementaryForm.sequenceName = this._get(res.data.data, 'sequenceDefinitionName', '');
        }

        //序列号规则
        this.$set(this.sequenceRuleInfo, 'name', this._get(res, 'data.data.sequenceDefinitionName', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(res, 'data.data.sequenceDefinitionFormat', ''));

        // this.$set(this.sequenceRuleInfo, 'sequenceNoFormatZh', this._get(res, 'data.data.sequenceNoFormatZh', ''));
        // this.$set(this.sequenceRuleInfo, 'seqNoFormatDemo', this._get(res, 'data.data.seqNoFormatDemo', ''));
        // this.$set(this.sequenceRuleInfo, 'containsSequenceNo', this._get(res, 'data.data.containsSequenceNo', true));
        // this.$set(this.sequenceRuleInfo, 'charactersCount', this._get(res, 'data.data.charactersCount', 0));

        this.seqNoConvert();
      });
    },
    // 生成 增补 获取已生成数量的接口
    getStartOrEndSequenceNumber(value) {
      let params = {
        sourceId: this.printWorkOrderId,
        sourceType: 'LABEL_PRODUCT_BY_WO'
      };
      sequenceGenerationSum(params).then(
        (res) => {
          if (value == 'generatedType') {
            this.cpgeneratedForm.hasquantity = res.data.data;
          } else {
            this.cpSupplementaryForm.hasquantity = res.data.data;
          }
        },
        (error) => {}
      );
    },
    preview(row, quantity) {
      if (row.sequenceDefinitionId == '' || row.sequenceDefinitionId == null) {
        return;
      }
      let attr = {
        workOrderId: row.workOrderId,
        quantity: quantity,
        sequenceDefinitionId: row.sequenceDefinitionId
        // timeConfig: this.timeConfig
      };
      generationPreview(attr).then(
        (res) => {
          this.$set(this.sequenceRuleInfo, 'sequenceNo', this._get(res, 'data.data.startSequenceNo', ''));
          this.$set(this.sequenceRuleInfo, 'quantity', this._get(res, 'data.data.quantity', ''));
          this.$set(this.sequenceRuleInfo, 'sequenceNumberFrom', this._get(res, 'data.data.sequenceNumberFrom', ''));
          this.$set(this.sequenceRuleInfo, 'snLength', this._get(res, 'data.data.snLength', ''));
          this.$set(this.sequenceRuleInfo, 'sequenceNumberTo', this._get(res, 'data.data.sequenceNumberTo', ''));
        },
        (error) => {}
      );
    },
    compute() {
      console.log(this.cpScrapForm, 'this.cpScrapForm');
      // this.cpScrapForm.workOrderId
      let attr = {
        workOrderId: this.cpScrapForm.workOrderId,
        sequenceNumberFrom: this.cpScrapForm.startSequenceNumber,
        sequenceNumberTo: this.cpScrapForm.endSequenceNumber
      };
      count(attr).then(
        (res) => {
          const data = res.data.data;
          this.cpScrapForm.serialQuantity = data.count;
          this.cpScrapForm.sequenceGenerationId = data.generationId;
        },
        (error) => {}
      );
    },
    serialnoRowClick(row) {
      this.selectionInfo = row;
      if (this.labelPrintType == 'scrapType') {
        this.cpScrapForm.startSequenceNumber = row.sequenceNumberFrom;
        this.cpScrapForm.endSequenceNumber = row.sequenceNumberTo;
      }
      this.$refs.serialNoGenerationRecord.toggleSelection(row);
    },

    /**
     * 多选事件
     */
    // selectionChange(list) {
    //   this.selectionInfo = list;
    //   console.log(this.selectionInfo, ' this.selectionInfo');
    // },
    /*
     * 序列号规则转换中文
     * @param sequenceNoValue 序列号规则
     * @param sequenceNo 序列号规则起始流水号
     */
    seqNoConvert() {
      let seqNoRules = [];
      this._forEach(getSeqNoRules(), (item) => {
        seqNoRules = [...seqNoRules, ...item.value];
      });
      let splitList = this.sequenceRuleInfo.sequenceNoFormat.split('');
      //在[前加空格  ]后加空格
      splitList = splitList.map((item) => {
        if (item === '[') {
          return ' [';
        } else if (item === ']') {
          return '] ';
        } else {
          return item;
        }
      });
      splitList = splitList.join('');
      //按空格拆分字符串
      splitList = splitList.split(' ');
      //匹配中文
      let splitArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            item = ele.value;
          }
        });
        return item;
      });
      //去除空格
      splitArr = splitArr.filter(function (s) {
        return s && s.trim();
      });
      //转换后给序列号规则赋值
      this.sequenceRuleInfo.sequenceNoFormatZh = splitArr.join('+');

      let splitDemoArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            let currentDate = new Date();
            switch (item) {
              case '[YY]':
                let year = String(currentDate.getFullYear());
                item = year.substring(2, year.length);
                break;
              case '[YYYY]':
                item = currentDate.getFullYear();
                break;
              case '[M]':
                let month = currentDate.getMonth() + 1;
                if (month < 10) {
                  item = '0' + month;
                } else {
                  item = month;
                }
                break;
              case '[W]':
                let today = new Date();
                let firstDay = new Date(today.getFullYear(), 0, 1);
                let dayOfWeek = firstDay.getDay();
                let spendDay = 1;
                if (dayOfWeek != 0) {
                  spendDay = 7 - dayOfWeek + 1;
                }
                firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
                let d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
                let week = Math.ceil(d / 7);
                week = week + 1;
                if (week < 10) {
                  item = '0' + week;
                } else {
                  item = week;
                }
                break;
              case '[D]':
                let day = currentDate.getDate();
                if (day < 10) {
                  item = '0' + day;
                } else {
                  item = day;
                }
                break;
              case '[S]':
                if (this.sequenceRuleInfo.sequenceNo) {
                  item = this.sequenceRuleInfo.sequenceNo;
                } else {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
              case '[WO]':
                if (this.model.workOrderNo) {
                  item = this.model.workOrderNo;
                } else {
                  item = '[WO]';
                }
                break;
              default:
                if (ele.code) {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
            }
          }
        });
        return item;
      });
      splitDemoArr = splitDemoArr.filter(function (item) {
        return String(item) && String(item).trim();
      });
      this.sequenceRuleInfo.seqNoFormatDemo = splitDemoArr.join('');
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
        const dataId = printInfo.dataId;
        if (dataId) {
          this.getDetail(printInfo.dataId);
        } else {
          this.fieldList = [];
        }
      }
    },
    /**
     * 打开选择工单号模态框
     */
    openCommonModal() {
      let url = '/api/mes-product/work-order/page';
      this.modalName = 'workorderModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        titleInfo: 'workorderModal',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '生产工单',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'type',
            span: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity',
            type: 'number',
            minRows: 1
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true,
            searchType: 'input',
            type: 'search'
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            search: true
          },
          {
            label: '产品规格',
            prop: 'productPartModel',
            search: true
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion',
            type: 'search'
          },
          {
            label: '计划开始时间',
            prop: 'planStartTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '计划结束时间',
            prop: 'planEndTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '制定人',
            prop: 'creator',
            disabled: true
          },
          {
            label: '状态',
            prop: 'status',
            span: 8,
            type: 'select',
            dataType: 'string',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=mfg_work_order'
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea'
          }
        ]
      };
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?subType=WORK_IN_PROGRESS&type=MATERIAL',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '进制符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },

    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?type=MATERIAL&subType=WORK_IN_PROGRESS&status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    },

    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 根据id获取所有生成记录
     */
    getSequenceRecordById(id, type) {
      let params = {
        sourceId: id,
        sourceType: 'LABEL_PRODUCT_BY_WO'
      };
      this.loading = true;
      getSourceList(params, this.serialnoPage.currentPage, this.serialnoPage.pageSize)
        .then(
          (res) => {
            let data = this._get(res, 'data.data', []);
            this.serialnoPage.total = data.total;
            this.serialnoData = data.records;
            if (['generatedType', 'supplementaryType'].includes(this.labelPrintType) && this.serialnoData.length && this.serialnoData[0].isPrinted === 0) {
              this.serialnoRowClick(this.serialnoData[0]);
            }
          },
          (error) => {
            this.serialnoData = [];
          }
        )
        .finally((this.loading = false));
    },
    //置换序列号回车
    onceMore(value) {
      sequenceNumber(value).then(
        (res) => {
          if (res.data.code == 200) {
            let rowData = res.data.data;
            this.cpReplacementForm.workOrderNo = this._get(rowData, 'workOrderNo', '');
            this.cpReplacementForm.partNo = this._get(rowData, 'productPartNo', '');
            this.cpReplacementForm.partName = this._get(rowData, 'productPartName', '');
            this.cpReplacementForm.partModel = this._get(rowData, 'productPartModel', '');
            this.cpReplacementForm.quantity = this._get(rowData, 'planQuantity', '');
            this.getSequenceRecordById(this._get(rowData, 'workOrderId', ''), 'REPLACE');
            // let id = this._get(rowData, 'sequenceGenerationId', '');
            // this.print(id);
          } else {
            this.cpReplacementForm.workOrderNo = '';
            this.cpReplacementForm.partNo = '';
            this.cpReplacementForm.partName = '';
            this.cpReplacementForm.partModel = '';
            this.cpReplacementForm.quantity = '';
          }
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    printInputInfo(otherInfo) {
      if (this.labelPrintType === 'replacementType') {
        this.handleReplacementGeneratePrint(otherInfo);
      } else {
        this.handlePrintSequence(otherInfo);
      }
    },
    print(partNo) {
      getLastPrintRecord({ partNo }).then(
        (res) => {
          let { labelTemplateId = '', printerId = '', equipmentName = '', labelTemplateName = '' } = res.data;
          this.repeatPrintInfo = {
            labelTemplateId: labelTemplateId,
            labelTemplateName: labelTemplateName,
            equipmentId: printerId,
            equipmentName
          };
        },
        (error) => {
          showFailLog(error.data.msg);
        }
      );
    },
    queryWorkOrderInfo(workOrderNo) {
      if (!workOrderNo) {
        return;
      }
      getWorkOrderDetail(workOrderNo).then((res) => {
        let workOrderInfo = this._get(res, 'data.data', {});
        this.printWorkOrderId = workOrderInfo.id;
        switch (this.labelPrintType) {
          case 'generatedType':
            this.cpgeneratedForm.partMasterId = workOrderInfo.partMasterId;

            this.cpgeneratedForm.workOrderId = workOrderInfo.id;
            this.cpgeneratedForm.workOrderNo = workOrderInfo.workOrderNo;

            this.cpgeneratedForm.partNo = workOrderInfo.productPartNo;
            this.cpgeneratedForm.partName = workOrderInfo.productPartName;
            this.cpgeneratedForm.partModel = workOrderInfo.productPartModel;

            this.cpgeneratedForm.sequenceDefinitionId = workOrderInfo.productSequenceDefinitionId;
            this.cpgeneratedForm.sequenceName = workOrderInfo.sequenceDefinitionName;
            this.cpgeneratedForm.quantity = workOrderInfo.planQuantity;

            // this.getSequencedefinitionDetail(this.cpgeneratedForm.partMasterId, 'generatedType');
            this.getStartOrEndSequenceNumber('generatedType');
            this.preview(this.cpgeneratedForm, 1);
            this.getSequenceRecordById(workOrderInfo.id, 'NORMAL');
            break;
          case 'supplementaryType':
            this.cpSupplementaryForm.partMasterId = workOrderInfo.partMasterId;

            this.cpSupplementaryForm.workOrderId = workOrderInfo.id;
            this.cpSupplementaryForm.workOrderNo = workOrderInfo.orderNo;

            this.cpSupplementaryForm.partNo = workOrderInfo.productPartNo;
            this.cpSupplementaryForm.partName = workOrderInfo.productPartName;
            this.cpSupplementaryForm.partModel = workOrderInfo.productPartModel;

            this.cpSupplementaryForm.sequenceDefinitionId = workOrderInfo.productSequenceDefinitionId;
            this.cpSupplementaryForm.sequenceName = workOrderInfo.sequenceDefinitionName;
            this.cpSupplementaryForm.quantity = workOrderInfo.planQuantity;

            this.getSequencedefinitionDetail(this.cpSupplementaryForm.partMasterId, 'supplementaryType');
            this.getStartOrEndSequenceNumber('supplementaryType');
            this.preview(this.cpSupplementaryForm, 1);
            this.getSequenceRecordById(workOrderInfo.id, 'APPEND');
            break;
          case 'scrapType':
            this.cpScrapForm.workOrderId = workOrderInfo.id;
            this.cpScrapForm.workOrderNo = workOrderInfo.orderNo;
            this.cpScrapForm.partNo = workOrderInfo.productPartNo;
            this.cpScrapForm.partName = workOrderInfo.productPartName;
            this.cpScrapForm.partModel = workOrderInfo.productPartModel;
            this.cpScrapForm.sequenceDefinitionId = workOrderInfo.productSequenceDefinitionId;
            this.cpScrapForm.sequenceName = workOrderInfo.sequenceDefinitionName;
            this.cpScrapForm.quantity = workOrderInfo.planQuantity;
            if (this.cpScrapForm.sequenceDefinitionId) {
              this.getSequencedefinitionDetail(this.cpScrapForm.sequenceDefinitionId);
            }
            this.getSequenceRecordById(workOrderInfo.id, 'SCRAP');

            break;
          default:
            break;
        }
      });
    }
  }
};

/*
 **   产品标签生成 option数据
 **
 */
export const generatedDataOption = (safe) => {
  return {
    labelPosition: 'right',
    labelWidth: 200,
    // menuBtn: true,
    submitBtn: false,
    submitText: '生成标签',
    emptyBtn: false,
    menuPosition: 'right',
    column: [
      {
        label: '工单号',
        prop: 'workOrderNo',
        span: 18,
        type: 'search',
        placeholder: '请选择 工单号',
        rules: [
          {
            required: true,
            message: '请选择 工单号',
            trigger: 'blur'
          }
        ],
        appendClick: () => {
          safe.openCommonModal();
        },
        enter: (value) => {
          safe.queryWorkOrderInfo(value);
        }
      },
      {
        label: '产品编码',
        span: 18,
        prop: 'partNo',
        disabled: true,
        placeholder: '产品编码'
      },
      {
        label: '产品名称',
        span: 18,
        prop: 'partName',
        disabled: true,
        placeholder: '产品名称'
      },
      {
        label: '产品型号',
        span: 18,
        prop: 'partModel',
        disabled: true,
        placeholder: '物料名称'
      },

      {
        label: '生产总数',
        span: 18,
        prop: 'quantity',
        disabled: true
      },
      {
        label: '已生成数量',
        span: 18,
        prop: 'hasquantity',
        disabled: true
      },
      {
        label: '序列号规则',
        prop: 'sequenceName',
        type: 'search',
        disabled: true,
        placeholder: '请选择 条码规则',
        span: 18,
        rules: [
          {
            required: true,
            message: '请选择 条码规则',
            trigger: 'blur'
          }
        ],
        appendClick: () => {
          safe.openSerialnoCommonModal();
        }
      },
      {
        label: '本次生成数量',
        prop: 'produceQuantity',
        span: 18,
        placeholder: '请输入本次生产数量',
        rules: [
          {
            required: true,
            message: '请输入本次生产数量',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              let reg = /^\+?[1-9]\d*$/;
              if (!reg.test(value)) {
                callback(new Error('请输入正整数'));
              } else {
                callback();
              }
            }
          }
        ],
        change: ({ value }) => {
          if (value) {
            safe.preview(safe.cpgeneratedForm, value);
          }
        }
      }
    ]
  };
};
/*
 **   产品标签增补 option数据
 **
 */
export const supplementaryDataOption = (safe) => {
  return {
    labelPosition: 'right',
    labelWidth: 200,
    labelHeight: 60,
    submitBtn: false,
    submitText: '生成标签',
    emptyBtn: false,
    menuPosition: 'right',
    column: [
      {
        label: '工单号',
        prop: 'workOrderNo',
        span: 18,
        type: 'search',
        placeholder: '请选择 工单号',
        rules: [
          {
            required: true,
            message: '请选择 工单号',
            trigger: 'blur'
          }
        ],
        appendClick: () => {
          safe.openCommonModal();
        },
        enter: (value) => {
          safe.queryWorkOrderInfo(value);
        }
      },
      {
        label: '产品编码',
        span: 18,
        prop: 'partNo',
        disabled: true,
        placeholder: '产品编码'
      },
      {
        label: '产品名称',
        span: 18,
        prop: 'partName',
        disabled: true,
        placeholder: '产品名称'
      },
      {
        label: '产品型号',
        span: 18,
        prop: 'partModel',
        disabled: true,
        placeholder: '产品型号'
      },

      {
        label: '生产总数',
        span: 18,
        prop: 'quantity',
        disabled: true
      },
      {
        label: '已生成数量',
        span: 18,
        prop: 'hasquantity',
        disabled: true
      },
      {
        label: '序列号规则',
        prop: 'sequenceName',
        type: 'search',
        placeholder: '请选择 条码规则',
        span: 18,
        rules: [
          {
            required: true,
            message: '请选择 条码规则',
            trigger: 'blur'
          }
        ],
        appendClick: () => {
          safe.openSerialnoCommonModal();
        }
      },
      {
        label: '本次生成数量',
        prop: 'produceQuantity',
        span: 18,
        placeholder: '请输入本次生产数量',
        rules: [
          {
            required: true,
            message: '请输入本次生产数量',
            trigger: 'blur'
          },
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              let reg = /^\+?[1-9]\d*$/;
              if (!reg.test(value)) {
                callback(new Error('请输入正整数'));
              } else {
                callback();
              }
            }
          }
        ],
        change: ({ value }) => {
          if (value) {
            safe.preview(safe.cpSupplementaryForm, value);
          }
        }
      },
      {
        label: '原因说明',
        span: 18,
        prop: 'remark',
        placeholder: '请输入原因说明',
        rules: [
          {
            required: true,
            message: '请输入原因说明',
            trigger: 'blur'
          }
        ]
      }
    ]
  };
};
/*
 **   产品标签置换 option数据
 **
 */
export const replacementDataOption = (safe) => {
  return {
    labelPosition: 'right',
    labelWidth: 200,
    labelHeight: 60,
    submitBtn: false,
    submitText: '生成标签',
    emptyBtn: false,
    menuPosition: 'right',
    column: [
      {
        label: '旧产品标签',
        prop: 'replaceSequenceNumber',
        span: 18,
        placeholder: '请输入旧产品标签',
        rules: [
          {
            required: true,
            message: '请输入旧产品标签',
            trigger: 'blur'
          }
        ],
        enter: (val) => {
          safe.onceMore(val);
        }
      },
      {
        label: '工单号',
        prop: 'workOrderNo',
        span: 18,
        disabled: true,
        placeholder: ' 工单号'
      },
      {
        label: '产品编码',
        span: 18,
        prop: 'partNo',
        disabled: true,
        placeholder: '产品编码'
      },
      {
        label: '产品名称',
        span: 18,
        prop: 'partName',
        disabled: true,
        placeholder: '产品名称'
      },
      {
        label: '产品型号',
        span: 18,
        prop: 'partModel',
        disabled: true,
        placeholder: '产品型号'
      },

      {
        label: '生产总数',
        span: 18,
        prop: 'quantity',
        disabled: true
      },

      {
        label: '原因说明',
        span: 18,
        prop: 'reason',
        placeholder: '请输入原因说明',
        rules: [
          {
            required: true,
            message: '请输入原因说明',
            trigger: 'blur'
          }
        ]
      }
    ]
  };
};
/*
 **   产品标签报废 option数据
 **
 */

export const scrapDataOption = (safe) => {
  return {
    labelPosition: 'right',
    labelWidth: 200,
    // menuBtn: true,
    submitBtn: false,
    submitText: '生成标签',
    emptyBtn: false,
    menuPosition: 'right',
    column: [
      {
        label: '工单号',
        prop: 'workOrderNo',
        span: 18,
        type: 'search',
        placeholder: '请选择 工单号',
        rules: [
          {
            required: true,
            message: '请选择 工单号',
            trigger: 'blur'
          }
        ],
        appendClick: () => {
          safe.openCommonModal();
        },
        enter: (value) => {
          safe.queryWorkOrderInfo(value);
        }
      },
      {
        label: '产品编码',
        span: 18,
        prop: 'partNo',
        disabled: true,
        placeholder: '产品编码'
      },
      {
        label: '产品名称',
        span: 18,
        prop: 'partName',
        disabled: true,
        placeholder: '产品名称'
      },
      {
        label: '产品型号',
        span: 18,
        prop: 'partModel',
        disabled: true,
        placeholder: '物料名称'
      },

      {
        label: '生产总数',
        span: 18,
        prop: 'quantity',
        disabled: true
      },
      {
        label: '起始序列号',
        prop: 'startSequenceNumber',
        span: 18,
        placeholder: '请输入起始序列号',
        rules: [
          {
            required: true,
            message: '请输入起始序列号',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '结尾序列号',
        prop: 'endSequenceNumber',
        span: 18,
        placeholder: '请输入结尾序列号',
        rules: [
          {
            required: true,
            message: '请输入结尾序列号',
            trigger: 'blur'
          }
        ],
        enter: (value) => {
          safe.compute();
        }
      },
      {
        label: '序列号数量',
        span: 18,
        prop: 'serialQuantity',
        disabled: true
      },
      {
        label: '原因说明',
        span: 18,
        prop: 'reason',
        placeholder: '请输入原因说明',
        rules: [
          {
            required: true,
            message: '请输入原因说明',
            trigger: 'blur'
          }
        ]
      }
    ]
  };
};
</script>

<style scoped lang="scss">
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;

    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }

    tr {
      border: 1px solid #ebeef5;
    }

    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }

    p {
      margin-left: 30px;
    }
  }
}

.newFormStyle {
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 15px;
  }

  ::v-deep .el-input--small input {
    height: 30px;
    line-height: 30px;
  }
}

.generateSerialNoInfo {
  div {
    margin: 5px 10px;
  }
}

.printButton {
  text-align: right;
}

.btn-group {
  display: flex;
  justify-content: center;
}
</style>
